<?php

namespace frontend\controllers;

use Yii;
use frontend\models\ResumeForm;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use Knp\Snappy\Image;
use Knp\Snappy\Pdf;

/**
 * ResumeController implements the CRUD actions for ResumeForm model.
 */
class ResumeController extends Controller
{
    public $layout = 'template';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                // 'only' => ['index', 'create','update'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all ResumeForm models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => ResumeForm::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ResumeForm model.
     * @param integer $id
     * @return mixed
     */
    public function actionView()
    {
        $resume=$this->getMyResume();

        $data['cname'] = $resume['cnName'];
        $data['ename'] = $resume['enName'];
        $data['sex'] = $resume['sex'];
        $data['housereg'] = $resume['housereg'];
        $data['birthday'] = $resume['birthday'];
        $data['phone'] = $resume['phone'];
        $data['email'] = $resume['email'];
        $data['educationinfo'] = $this->getUnSerialize($resume['educationinfo']);
        $data['workhistory'] = $this->getUnSerialize($resume['workhistory']);
        $data['selfevaluation'] = $resume['selfevaluation'];
        $data['selftags'] = $resume['selftags'];
        $data['supplement'] = $this->getUnSerialize($resume['supplement']);

        return Json::encode($data);
    }

    /**
     * Creates a new ResumeForm model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($act='base')
    {
        $request = Yii::$app->request;
        $requestPost = $request->post();
        if ($request->isAjax && $requestPost) {
            try{
                $id = Yii::$app->user->id;
                if($model = $this->getMyResume()){
                    //update action
                }else{
                    $model = new ResumeForm();  //new add action
                }
                $model->uid = Yii::$app->user->identity->id;
                switch($act){
                    case 'educate':    //教育背景
                        $model->educationinfo = serialize($requestPost);
                        break;
                    case 'work';    //工作经历
                        $model->workhistory = serialize($requestPost);
                        break;
                    case 'other';   //奖项，证书,等
                        $model->supplement = serialize($requestPost);
                        break;
                    case 'valuate';  //自我评价\
                        $model->selfevaluation = $requestPost['selfevaluation'];
                        break;
                    case 'tags';    //个性标签
                        $model->selftags = $requestPost['selftags'];
                        break;
                    case 'base';    //个人资料
                        $model->cnName = $requestPost['cnname'];
                        $model->enName = $requestPost['enname'];
                        $model->sex = $requestPost['sex'];
                        $model->housereg = $requestPost['housereg'];
                        $model->birthday = $requestPost['birthday'];
                        $model->phone = $requestPost['phone'];
                        $model->email = $requestPost['email'];
                        break;
                    default:
                        throw new BadRequestHttpException();
                }
                if($model->save()){
                    return $this->responseJson('y');
                }
                return $this->responseJson('n');
            }catch (Exception $e){
                return $this->responseJson('n');
            }
        }
    }

    public  function actionPdf($template=1)
    {
        $fileName = 'resume';
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' .$fileName. '.pdf"');

        $pdf = new Pdf('wkhtmltopdf');
        $pdf->setOption('encoding','utf-8');
        $pdf->setOption('margin-top',0);
        $pdf->setOption('margin-left',0);
        $pdf->setOption('margin-right',0);
        $pdf->setOption('margin-bottom',0);
        $pdf->setTemporaryFolder('/www/yii2lh/tmp');
        $htmlContent = $this->render('template',['model'=>$this->getMyResume(),'tid'=>$template]);
        return $pdf->getOutputFromHtml($htmlContent);
    }

    public function actionJpg($template=1)
    {
        $fileName = 'resume';
        header('Content-Type: image/jpeg');
        header('Content-Disposition: attachment; filename="' .$fileName. '.jpg"');

        $img = new Image('wkhtmltoimage');
        $img->setOption('width',792);
        $img->setOption('quality',100);
        $img->setTemporaryFolder('/www/yii2lh/tmp');
        $img->setOption('encoding','utf-8');
        $htmlContent = $this->render('template',['model'=>$this->getMyResume(),'tid'=>$template]);
        return $img->getOutputFromHtml($htmlContent);
    }

    public function actionIsCreate()
    {
        if($this->getMyResume())
        {
            return $this->responseJson('y','已创建');
        }
        return $this->responseJson('n','未创建');
    }

    /**
     * Finds the ResumeForm model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ResumeForm the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ResumeForm::findOne($id)) !== null) {
            return $model;
        }
        return null;
    }

    protected function getMyResume()
    {
        return $this->findModel( Yii::$app->user->identity->id );
    }

    protected  function responseJson( $status = 'n', $msg = '' )
    {
        if($status == 'y'){
            $msg = '提交成功';
        }
        if($status == 'n'){
            $msg = '提交失败';
        }
        return Json::encode( ['status'=> $status ,'msg'=> $msg] );
    }

    protected  function getUnSerialize($value)
    {
        $v = @unserialize($value);
        return $v!==false ? $v : '';
    }

}
